import { FlowPostItem } from '@/api/flow'
import { ElForm } from 'element-plus'
import { ref, Ref, computed } from 'vue'
import { flowsubmit, FormType } from '@/api/flow'
import { RouteLocationNormalizedLoaded } from 'vue-router'
import { useStore } from '@/store'
import dayjs from 'dayjs'

interface FormPlugin {
  fields: Ref<Array<FlowPostItem>>
  form: Ref<FormType>
  loading: Ref<boolean>
  handleSubmit: (name: string) => void
  resetForm: () => void
  setFormRef: (el: InstanceType<typeof ElForm>) => void
  rules: FormType
  formRef: Ref<InstanceType<typeof ElForm> | undefined>
  user: Ref<{
    vl: string | undefined
    pf: string
    nf: string
  }>
  searchSelected: (item: string) => void
  restaurants: Ref<RestaurantItem[]>
  execute_time: Ref<string>
}

interface RestaurantItem {
  name: string
  value: string
  pwd: string
}

const useForm = (router: RouteLocationNormalizedLoaded): FormPlugin => {
  const store = useStore()
  const arr = <Array<FlowPostItem>>router.meta.arguments
  const execute_time = ref()
  const restaurants = computed(() => store.state.permission.users)

  // 新增固定项: 预定执行时间
  const fields = ref([...arr])
  const asyncform: FormType = {}
  const rules: FormType = {}
  const user = ref({
    vl: undefined,
    nf: '',
    pf: ''
  })

  const userCheckRule = (rule: any, value: any, callback: any) => {
    if (!form.value[user.value.nf]) return callback(new Error('请输入用户名'))
    if (!form.value[user.value.pf]) return callback(new Error('请输入密码'))
    callback()
  }

  fields.value.forEach(f => {
    // 初始化表单字段
    if (f.type === 'user') {
      const u = <string>f.username_field
      const p = <string>f.password_field

      user.value.nf = u
      user.value.pf = p

      asyncform[u] = ''
      asyncform[p] = ''
      rules['user'] = [
        { required: true, validator: userCheckRule, trigger: 'blur' }
      ]
    } else {
      asyncform[f.name] = ''
      rules[f.name] = [
        { required: true, message: `${f.title}是必填项`, trigger: 'blur' }
      ]
    }
  })

  const form = ref(asyncform)

  const loading = ref(false)

  const formRef = ref<InstanceType<typeof ElForm>>()
  const setFormRef = (el: InstanceType<typeof ElForm>) => {
    formRef.value = el
  }

  const resetForm = () => {
    formRef.value?.resetFields()
  }
  const handleSubmit = (name: string) => {
    formRef.value?.validate(async valid => {
      if (valid) {
        loading.value = true
        const timestamp = execute_time.value
          ? dayjs(execute_time.value).unix()
          : undefined
        await flowsubmit(name, form.value, timestamp)
        // await pywebview.api.submit_flow(name as string, form.value)
        loading.value = false
      }
    })
  }

  const searchSelected = (val: string) => {
    if (!val) {
      form.value[user.value.nf] = undefined
      form.value[user.value.pf] = undefined
    } else {
      const item = restaurants.value.find(r => r.value === val)
      form.value[user.value.nf] = item.name
      form.value[user.value.pf] = item.pwd

      formRef.value?.clearValidate()
    }
  }

  return {
    fields,
    form,
    loading,
    handleSubmit,
    resetForm,
    setFormRef,
    rules,
    formRef,
    user,
    restaurants,
    searchSelected,
    execute_time
  }
}

export default useForm
